package com.gxa.insurance.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.insurance.exception.BusinessException;
import com.gxa.insurance.exception.ExceptionCode;
import com.gxa.insurance.pojo.Customer;
import com.gxa.insurance.pojo.Driver;
import com.gxa.insurance.service.AdminService;
import com.gxa.insurance.service.CustomerService;
import com.gxa.insurance.service.DriverService;
import com.gxa.insurance.util.JsonResult;
import com.gxa.insurance.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

/**
 * @author Min
 */
@RestController
@CrossOrigin
@RequestMapping("/msg")
public class SMSController {

    @Autowired
    private AdminService service;
    @Autowired
    private DriverService Dservice;
    @Autowired
    private CustomerService Cservice;

    @ApiOperation(value = "发送验证码的接口", produces = "query")
    @GetMapping("/sendPhone")
    public Map sendMsg(@RequestParam("phone") String phone,  HttpServletRequest req,HttpServletResponse resp) {
        // 确保手机号非空
        // 前端不管是否进行过校验,后端都要进行检验
        JsonResult jsonResult = new JsonResult();
        if (!StringUtil.isEmpty(phone)) {
            // 正则校验, 是否符合手机号格式,符合才发送短信,不符合给前端返回消息
            if (StringUtil.isPhoneNumber(phone)) {
                // 填写发送方的accessKey id 和 密钥
                DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tGSEWzS9RM8EjC2w8bK", "IaTDtee5wde5RLvl3qIEXBZxbcMPOm");
                IAcsClient client = new DefaultAcsClient(profile);
                // 验证手机号是否存在
                boolean byPhone = service.findByPhone(phone);
                if (!byPhone){
                    new BusinessException(ExceptionCode.WRONG_PHONE_NUMBER);
                }
                // 配置发送参数
                CommonRequest request = new CommonRequest();
                request.setSysMethod(MethodType.POST);
                request.setSysDomain("dysmsapi.aliyuncs.com");
                request.setSysVersion("2017-05-25");
                request.setSysAction("SendSms");
                request.putQueryParameter("RegionId", "cn-hangzhou");
                request.putQueryParameter("PhoneNumbers", phone);
                request.putQueryParameter("SignName", "小溪商城");
                request.putQueryParameter("TemplateCode", "SMS_204986028");

                // 生成4位随机数
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < 4; i++) {
                    builder.append(new Random().nextInt(8) + 1);
                }

                // 把验证码记录到session中
                HttpSession session = req.getSession();
                // 把验证码添加到session中
                session.setAttribute("captcha", builder.toString());
                // 把手机号添加session中
                session.setAttribute("phone", phone);

                // 作弊方式获取session存的验证码
                System.out.println("captcha:" + builder.toString());

                // 给阿里云短信模板中的${code}赋值，json格式
               request.putQueryParameter("TemplateParam", "{'code':" + builder.toString() + "}");
                try {
                    // 执行发送操作
                    CommonResponse response = client.getCommonResponse(request);
                    // 获取 阿里短信接口给当前的发送请求响应的数据
                    String data = response.getData();
                    //{"Message":"OK","RequestId":"CBC83055-A113-483A-91B2-0E4C56CCC643","BizId":"790710603115763709^0","Code":"OK"}

                    ObjectMapper mapper = new ObjectMapper();
                    Map<String, Object> tmpMap = mapper.readValue(data, Map.class);
                    // Code 为OK表示发送成功
                    if ("OK".equals(tmpMap.get("Code"))) {
                        // 给前端返回消息, 发送成功
                        jsonResult.setCode("1");
                        jsonResult.setMsg("发送成功");
                        return jsonResult.getMap();
                    } else {
                        // 传给统一异常处理器集中处理
                        new BusinessException(ExceptionCode.SEND_SMS_FAILED);
                    }

                } catch (Exception e) {
                    // 传给统一异常处理器集中处理
                    new BusinessException(ExceptionCode.SEND_SMS_FAILED);
                }

            } else {
                new BusinessException(ExceptionCode.WRONG_PHONE_NUMBER);
            }
        }
        jsonResult.setCode("0");
        jsonResult.setMsg("发送失败");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "发送邮件的接口 用户类型（用户和司机两种）和用户邮件选择发送一个参数 userType=1 司机  userType=2为用户",produces = "query")
    @PostMapping("/sendEmail")
    public Map sendEmail(@RequestParam(value = "message")String msgBody,@RequestParam(value = "sendUserType",required = false)String userType,
                         @RequestParam(value = "email",required = false)String userEmail) throws Exception {
        List<Driver> emails=null;
        List<Customer> customersE=null;
        if(!StringUtil.isEmpty(userType)){
            // 去查询所有此用户类型的邮箱
            if(userType.equals("1")){
                emails = Dservice.selectAllEmail();
            }else if(userType.equals("2")){
                customersE = Cservice.selectEmail();
            }
        }else if(!StringUtil.isEmpty(userEmail)){
            // 验证此邮箱是否存在
            Boolean isTrue=Cservice.selectByEmail(userEmail);
        }
        String from="878129931@qq.com";
        String[] to=null;
        if(emails!=null){
            to=new String[emails.size()];
            for (int i = 0; i < emails.size(); i++) {
                to[i]=emails.get(i).getEmail();
            }
        }else if(customersE!=null){
            to=new String[customersE.size()];
            for (int i = 0; i < customersE.size(); i++) {
                to[i]=customersE.get(i).getEmail();
            }
        }else{
            to=new String[]{userEmail};
        }
        // 发送邮件主机
        String host="smtp.qq.com";
        // 获取系统属性
        Properties properties = System.getProperties();
        // 添加发送主机
        properties.setProperty("mail.smtp.host",host);
        properties.put("mail.smtp.auth",true);
        // 获取默认Session
        Session session=Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("878129931@qq.com","nqreoqyxgmqgbdbb");
            }
        });

        // 准备发送的信息
        MimeMessage message=new MimeMessage(session);

        message.setFrom(new InternetAddress(from));
        InternetAddress[] internetAddresses = new InternetAddress[to.length];
        // 将有的要发送的邮箱添加进来
        for (int i = 0; i < to.length; i++) {
            InternetAddress internetAddress = new InternetAddress(to[i]);

            internetAddresses[i]=internetAddress;
        }

        message.addRecipients(Message.RecipientType.TO,internetAddresses);
        // 设置发送摘要
        message.setSubject("易理赔向您发送了一封邮件请及时查收,over");
        message.setText(msgBody);
        // 发送邮件
        Transport.send(message);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("推送成功");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "前台登录发送验证码的接口", produces = "query")
    @GetMapping("/sendPhoneCode")
    public Map sendPhoneCode(@RequestParam("phone") String phone,  HttpServletRequest req,HttpServletResponse resp) {
        // 确保手机号非空
        // 前端不管是否进行过校验,后端都要进行检验
        JsonResult jsonResult = new JsonResult();
        if (!StringUtil.isEmpty(phone)) {
            // 正则校验, 是否符合手机号格式,符合才发送短信,不符合给前端返回消息
            if (StringUtil.isPhoneNumber(phone)) {
                // 填写发送方的accessKey id 和 密钥
                DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tGSEWzS9RM8EjC2w8bK", "IaTDtee5wde5RLvl3qIEXBZxbcMPOm");
                IAcsClient client = new DefaultAcsClient(profile);
                // 验证手机号是否存在
                // 配置发送参数
                CommonRequest request = new CommonRequest();
                request.setSysMethod(MethodType.POST);
                request.setSysDomain("dysmsapi.aliyuncs.com");
                request.setSysVersion("2017-05-25");
                request.setSysAction("SendSms");
                request.putQueryParameter("RegionId", "cn-hangzhou");
                request.putQueryParameter("PhoneNumbers", phone);
                request.putQueryParameter("SignName", "小溪商城");
                request.putQueryParameter("TemplateCode", "SMS_204986028");

                // 生成4位随机数
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < 4; i++) {
                    builder.append(new Random().nextInt(8) + 1);
                }


                // 把验证码记录到session中
                HttpSession session = req.getSession();
                // 把验证码添加到session中
                session.setAttribute("captcha", builder.toString());
                // 把手机号添加session中
                session.setAttribute("phone", phone);

                // 作弊方式获取session存的验证码
                System.out.println("captcha:" + builder.toString());

                // 给阿里云短信模板中的${code}赋值，json格式
                request.putQueryParameter("TemplateParam", "{'code':" + builder.toString() + "}");
                try {
                    // 执行发送操作
                    CommonResponse response = client.getCommonResponse(request);
                    // 获取 阿里短信接口给当前的发送请求响应的数据
                    String data = response.getData();
                    //{"Message":"OK","RequestId":"CBC83055-A113-483A-91B2-0E4C56CCC643","BizId":"790710603115763709^0","Code":"OK"}

                    ObjectMapper mapper = new ObjectMapper();
                    Map<String, Object> tmpMap = mapper.readValue(data, Map.class);
                    // Code 为OK表示发送成功
                    if ("OK".equals(tmpMap.get("Code"))) {
                        // 给前端返回消息, 发送成功
                        jsonResult.setCode("1");
                        jsonResult.setMsg("发送成功");
                        return jsonResult.getMap();
                    } else {
                        // 传给统一异常处理器集中处理
                        new BusinessException(ExceptionCode.SEND_SMS_FAILED);
                    }

                } catch (Exception e) {
                    // 传给统一异常处理器集中处理
                    new BusinessException(ExceptionCode.SEND_SMS_FAILED);
                }

            } else {
                new BusinessException(ExceptionCode.WRONG_PHONE_NUMBER);
            }
        }
        jsonResult.setCode("0");
        jsonResult.setMsg("发送失败");
        return jsonResult.getMap();
    }
}
